const io  = require('socket.io-client');
const { ipcMain } = require('electron')
const window = require('./window')

const axios  = require('./axios');

module.exports = function (config){

    const numbers = {
        top : 0,
        bottom : 0
    }

    setInterval(() => {

        window.webContents.send('echarts', numbers)

        numbers.top = 0
        numbers.bottom = 0
        
    }, 1000)

    const socket = io(`ws://${config.host || '127.0.0.1'}:${config.port || '4000'}`)
    
    let keys = ['addRouter', 'socketInfo', 'delRouter']
    for (let index = 0; index < keys.length; index++) {
        const element = keys[index];
        socket.on(element, (data) => {
            window.webContents.send(element, data)
        })
        ipcMain.on(element, (e, data) => {
            socket.emit(element, data)
        })
    }

    function BytesCount(str){
        var cnt = 0;
        for(var i=0; i<str.length; i++){
            var c = str.charAt(i);
            if(/^[\u0000-\u00ff]$/.test(c)){
                cnt++;
            }else{
                cnt+=2;
            }
        }
        return cnt;
   
   }

    socket.on('send', (data) => {

        let bottom = BytesCount(JSON.stringify(data))

        numbers.bottom += bottom

        window.webContents.send('addRouterCount', data.path, bottom)

        axios(data).then(obj => {
            let top = BytesCount(JSON.stringify(obj))
            numbers.top = top
            window.webContents.send('addRouterCount', data.path, top)
            socket.emit('send', obj)
        })

        // axios({
        //     url : `http://${data.host}:${data.port}${data.url}`,
        //     method : data.method,
        //     data : data.data,
        //     headers: data.headers
        // }).then(res => {
        //     var obj = {
        //         success : true,
        //         code : data.code,
        //         data : res.data
        //     }
        //     let top = BytesCount(JSON.stringify(obj))
        //     numbers.top = top
        //     window.webContents.send('addRouterCount', data.path, top)
        //     socket.emit('send',obj)
        // }).catch(e => {
        //     let obj = {
        //         success : false,
        //         code : data.code,
        //         data : e
        //     }
        //     let top = BytesCount(JSON.stringify(obj))
        //     numbers.top = top
        //     window.webContents.send('addRouterCount', data.path, top)
        //     socket.emit('send', obj)
        // })

    })

    return socket
}